# gozerlib/tasks.py
#
#

## gozerlib imports 

from gozerlib.utils.trace import calledfrom
from gozerlib.plugins import plugs

## google imports

from google.appengine.ext.deferred import defer

## basic imports

import logging
import sys

class Task(object):

    def __init__(self, name, func):
        self.name = name
        self.func = func

    def handle(self, *args, **kwargs):
        self.func(*args, **kwargs)

class TaskManager(object):

    def __init__(self):
        self.handlers = {}
        self.plugins = {}

    def add(self, taskname, func):
        logging.debug("added task %s - %s" % (taskname, func))
        self.handlers[taskname] = func
        self.plugins[taskname] = calledfrom(sys._getframe())

    def dispatch(self, taskname, *args, **kwargs):
        plugin = self.plugins[taskname]
        logging.debug('loading %s for taskmanager' % plugin)
        plugs.reload(plugin)
        #logging.warn("args %s" % str(args))
        #logging.warn("kwargs %s" % str(kwargs))
        handler = self.handlers[taskname]
        logging.warn("dispatching task %s - %s" % (taskname, str(handler)))
        handler(*args, **kwargs)

taskmanager = TaskManager()
